from django.shortcuts import render
from rest_framework.views import APIView
import random, logging
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status

from . import constants
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.


logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """
    发送短信验证码
    传入参数：
    mobile, image_code_id,text
    """
    def get(self, request, mobile):
        # 创建redis对象
        print (mobile)
        redis_conn = get_redis_connection('verify_codes')

        # 判断用户是否是在６０秒内发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message':'发送短信频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 创建管道
        pl = redis_conn.pipeline()

        # 保存短信验证码
        # redis_conn.setex('sms_%s' % mobile, SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # 保存发送短信验证码的标记
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 执行
        pl.execute()

        # 集成容联云通讯发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, SMS_CODE_REDIS_EXPIRES // 60], 1)
        send_sms_code.delay(mobile, sms_code)
        # 响应结果
        print (sms_code)
        return Response({"message": "OK"})